﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using GraphAPI;

namespace GraphEditor
{
	internal class Algorithm
	{
		AppDomain domain;
		Assembly assembly;

		Type algorithmType = null;
		public Type AlgorithmType
		{
			get { return algorithmType; }
		}

		IAlgorithm algorithm = null;
		public IAlgorithm AlgorithmObject
		{
			get
			{
				if (algorithm == null)
					if (algorithmType != null)
						algorithm = assembly.CreateInstance(algorithmType.FullName) as IAlgorithm;

				return algorithm;
			}
		}

		private Type GetAlgorithmType(Assembly assembly)
		{
			foreach (Type type in assembly.GetTypes())
			{
				if (type.GetInterface(typeof(IAlgorithm).FullName) != null)
				{
					return type;
				}
			}

			return null;
		}

		public Algorithm(string assemblyPath)
		{
			domain = AppDomain.CreateDomain(assemblyPath);
			assembly = domain.Load(AssemblyName.GetAssemblyName(assemblyPath));

			algorithmType = GetAlgorithmType(assembly);

			if (algorithmType == null && algorithmType == null)
				throw new Exception("No algorithm class found.");
		}

		public void Unload()
		{
			AppDomain.Unload(domain);
		}
	}
}
